class CommentController < ApplicationController

  before_filter :set_object

  # add
  def add
      object_added = false;
      case @object_type
          when 'project'
              object_added = add_to_project;
	  when 'iteration'    
              object_added = add_to_iteration;
	  when 'task'    
              object_added = add_to_task;
      end

      #redirect_to(:controller => '', :action => '') if object_added;
  end

  # list
  def list
      comment_list = nil;
      case @object_type
          when 'project'
              comment_list = @project.comments;
	  when 'iteration'    
              comment_list = @iteration.comments;
	  when 'task'    
              comment_list = @task.comments;
      end 
      @comments = comment_list;
  end

  protected
  
  # decide the object for the request: project, iteration or task and get that object
  def set_object
      if params[:project_id] 
          @project = get_project(params[:project_id]);
          @object_type = 'project';  
      end	  
      if params[:iteration_id]
          @iteration = get_iteration(params[:iteration_id]);
          @object_type = 'iteration';
      end 
      if params[:task_id]
          @task = get_task(params[:task_id]);
          @object_type = 'task';
      end
  end


  def add_to_project
      return unless params[:form_submitted];
      # build hash
      attributes = params[:project];
      # insert comment
      return insert_comment(attributes);
  end

  def add_to_iteration
      return unless params[:form_submitted];
      # build hash
      attributes = params[:iteration];
      # insert comment
      return insert_comment(attributes);
  end

  def add_to_task
      return unless params[:form_submitted];
      # build hash
      attributes = params[:task];
      # insert comment
      return insert_comment(attributes);
  end

  def insert_comment(attributes)
      # add comment to the database  
      @comment = Comment.new(attributes);
      return false unless @comment.save();
      return true;
  end
end
